package com.zlsy.secondtime.background;

import java.util.concurrent.TimeUnit;

/**
 * @author zhouliang
 * @date 2020/05/23
 **/
public class MultiThreadError implements Runnable {

    static Object lock1 = new Object();
    static Object lock2 = new Object();
    private int flag = 1;

    @Override
    public void run() {
        if (flag == 1) {
            //因为我们new了两个对象，我们得保证对象不一样但是竞争的锁得一样。所以这里应当是一个类锁。
            synchronized (lock1) {
                System.out.println(Thread.currentThread().getName() + "获取到lock1，准备获取lock2.");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    System.out.println(Thread.currentThread().getName() + "获取到lock2");
                }
                System.out.println(Thread.currentThread().getName() + "运行结束！");
            }
        }
        if (flag == 2) {
            synchronized (lock2) {
                System.out.println(Thread.currentThread().getName() + "获取到lock2，准备获取lock1.");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println(Thread.currentThread().getName() + "获取到lock1");
                }
                System.out.println(Thread.currentThread().getName() + "运行结束！");
            }
        }
    }

    public static void main(String[] args) {
        MultiThreadError r1 = new MultiThreadError();
        r1.flag = 1;
        Thread a = new Thread(r1);
        a.setName("线程1");

        MultiThreadError r2 = new MultiThreadError();
        r2.flag = 2;
        Thread b = new Thread(r2);
        b.setName("线程2");

        a.start();
        b.start();
    }
}
